<template>
    <div>
        <el-card class="!border-none" shadow="never">
            <el-page-header :content="$route.meta.title" @back="$router.back()" />
        </el-card>
        <el-card class="mt-4 !border-none" shadow="never">
            <!-- <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
                <el-tab-pane label="基本信息" :name="1">User</el-tab-pane>
                <el-tab-pane label="" :name="2">Config</el-tab-pane>
                <el-tab-pane label="Role" :name="3">Role</el-tab-pane>
                <el-tab-pane label="Task" :name="4">Task</el-tab-pane>
            </el-tabs> -->

            <el-form class="ls-form" label-width="100px"  ref="formRef" :model="formData">
                <div class="xl:flex flex-row" style="flex-wrap: wrap;">
                    <template v-for="(item, index) in columnArr" :key="index">
                        <el-form-item :label="item.name" :prop="item.column_name">
                            <div class="w-80">
                                <div v-if="item.type == 'input'">
                                    <el-input v-model="formData[item.column_name]" :placeholder="'请输入' + item.name"
                                        type="data" show-word-limit clearable style="width: 100%;height: 40px;" />
                                </div>
                                <div v-else-if="item.type == 'checkbox'">
                                    <el-radio-group v-model="formData[item.column_name]">
                                        <el-radio :value="1">是</el-radio>
                                        <el-radio :label="0">否</el-radio>
                                    </el-radio-group>
                                </div>
                            </div>
                        </el-form-item>
                    </template>
                    <template v-for="(item, index) in limits" :key="index">
                        <el-form-item :label="item.name" :prop="item.column_name" v-perms="[item.limit]">
                            <div class="w-80">
                                <div v-if="item.type == 'input'">
                                    <el-input v-model="formData[item.column_name]" :placeholder="'请输入' + item.name"
                                        type="data" show-word-limit clearable style="width: 100%;height: 40px;" />
                                </div>
                                <div v-else-if="item.type == 'checkbox'">
                                    <el-radio-group v-model="formData[item.column_name]">
                                        <el-radio :value="1">是</el-radio>
                                        <el-radio :label="0">否</el-radio>
                                    </el-radio-group>
                                </div>
                            </div>
                        </el-form-item>
                    </template>
                </div>
                <el-form-item label="下单商品" v-perms="['order.orderGoods']">
                    <template #default="{ row }">
                        <div class="config-form">
                            <el-form
                                v-for="(item, index) in formData.skus"
                                :ref="(el) => setSkuFormRef(index, el)"
                                class="ls-form"
                                :inline="true"
                                :model="item"
                                
                                style="display: flex;align-items: flex-start;flex-wrap: wrap;gap: 30px 0;" :rules="configItemRule"
                            >
                                <el-form-item label="选择商品规格" prop="sku_id" label-width="120px">
                                    <el-select v-model="item.sku_id" :data-index="index" @change="selectChange(item, index, $event)"
										placeholder="请选择" size="large" class="config-key-input" filterable>
										<el-option
											v-for="(item1, index1) in skusData"
											:label="item1.name" :value="item1.id" />
									</el-select>
                                </el-form-item>
                                <el-form-item label="单位" prop="unit" label-width="120px">
                                    <el-input
                                        v-model="item.unit"
                                        placeholder="请输入"
                                        class="config-key-input"
                                    />
                                </el-form-item>
                                <el-form-item label="规格" prop="name" label-width="120px">
                                    <el-input
                                        v-model="item.name"
                                        placeholder="请输入"
                                        class="config-key-input"
                                    />
                                </el-form-item>
                                <el-form-item label="颜色" prop="color" label-width="120px">
                                    <el-input
                                        v-model="item.color"
                                        placeholder="请输入"
                                        class="config-key-input"
                                    />
                                </el-form-item>
                                <el-form-item label="型号" prop="type" label-width="120px">
                                    <el-input
                                        v-model="item.type"
                                        placeholder="请输入"
                                        class="config-key-input"
                                    />
                                </el-form-item>
                                
                                <el-form-item label="盖帽颜色" prop="hat_color" label-width="120px">
                                    <el-input
                                        v-model="item.hat_color"
                                        placeholder="请输入"
                                        class="config-key-input"
                                    />
                                </el-form-item>
                                <el-form-item label="接口口径" prop="caliber" label-width="120px">
                                    <el-input
                                        v-model="item.caliber"
                                        placeholder="请输入"
                                        class="config-key-input"
                                    />
                                </el-form-item>
                                <el-form-item label="系列" prop="series" label-width="120px">
                                    <el-input
                                        v-model="item.series"
                                        placeholder="请输入"
                                        class="config-key-input"
                                    />
                                </el-form-item>
                                <el-form-item label="进水方式" prop="method" label-width="120px">
                                    <el-input
                                        v-model="item.method"
                                        placeholder="请输入"
                                        class="config-key-input"
                                    />
                                </el-form-item>
                                <el-form-item label="特殊型号" prop="special_type" label-width="120px">
                                    <el-input
                                        v-model="item.special_type"
                                        placeholder="请输入"
                                        class="config-key-input"
                                    />
                                </el-form-item>
                                <el-form-item label="高度" prop="height" label-width="120px">
                                    <el-input
                                        v-model="item.height"
                                        placeholder="请输入"
                                        class="config-key-input"
                                    />
                                </el-form-item>
                                <el-form-item label="片数" prop="number" label-width="120px">
                                    <el-input
                                        v-model="item.number"
                                        placeholder="请输入"
                                        class="config-key-input"
                                        type="number"
                                    />
                                </el-form-item>
                                <el-form-item label="组数" prop="group_number" label-width="120px">
                                    <el-input
                                        v-model="item.group_number"
                                        placeholder="请输入"
                                        class="config-key-input"
                                        type="number"
                                    />
                                </el-form-item>
                                <!-- <el-form-item label="总数" prop="total_number" label-width="120px">
                                    <el-input
                                        v-model="item.total_number"
                                        placeholder="请输入"
                                        class="config-key-input"
                                        type="number"
                                    />
                                </el-form-item> -->
                                <el-form-item label="销售单价" prop="sale_price" label-width="120px">
                                    <el-input
                                        v-model="item.sale_price"
                                        placeholder="请输入"
                                        class="config-key-input"
                                    />
                                </el-form-item>
                                <el-form-item label="成本单价" prop="cost_price" label-width="120px">
                                    <el-input
                                        v-model="item.cost_price"
                                        placeholder="请输入"
                                        class="config-key-input"
                                    />
                                </el-form-item>
                                
                                <el-form-item label="备注" prop="remark" label-width="120px">
                                    <el-input
                                        v-model="item.remark"
                                        placeholder="请输入"
                                        class="config-key-input"
                                    />
                                </el-form-item>
                                <el-form-item label="颜色" prop="color" label-width="120px">
                                    <el-input
                                        v-model="item.color"
                                        placeholder="请输入"
                                        class="config-key-input"
                                    />
                                </el-form-item>
                                <el-form-item prop="sale_number">
                                    <el-button type="danger" @click="formData.skus.splice(index, 1)"
                                        >删除规格</el-button
                                    >
                                </el-form-item>
                            </el-form>

                            <el-button type="primary" @click="addConfigItem">添加配置项</el-button>
                        </div>
                    </template>
                    
                </el-form-item>
                <el-form-item label="资料上传">
                    <material-picker v-model="formData.info_photos" :limit="30" />
                </el-form-item>
                <el-divider />
                <!-- 测量列表 -->
                <div v-if="formData.is_measure == 1" v-perms="['order.measurement']">
                    <el-button type="primary" @click="addMeasureItem">添加测量项</el-button>
                </div>
                <div  class="xl:flex flex-row" style="flex-wrap: wrap;" v-if="formData.is_measure == 1" v-perms="['order.measurement']">
                    <template v-for="(item, index) in measureCoForm.list" :key="index">
                        <el-form :model="item" label-width="80px">
                            <div  class="xl:flex flex-row" style="flex-wrap: wrap;">
                                <el-form-item label="测量时间" :prop="item.measure_time" style="display: flex;align-items: flex-start;">
                                    <div class="w-[200px]">
                                        <el-date-picker v-model="item.measure_time" type="date" placeholder="选择日期"
                                            format="YYYY-MM-DD" value-format="x" style="width: 100%;height: 40px;">
                                        </el-date-picker>
                                    </div>
                                </el-form-item>
                                <el-form-item label="测量师傅" :prop="item.measure_name" style="display: flex;align-items: flex-start;">
                                    <div class="w-[200px]">
                                        <el-input v-model="item.measure_name" :placeholder="'请输入测量师傅'" type="data" show-word-limit clearable style="width: 100%;height: 40px;box-sizing: border-box;" />
                                    </div>
                                </el-form-item>
                                <el-form-item label="师傅电话" :prop="item.measure_mobile" style="display: flex;align-items: flex-start;">
                                    <div class="w-[200px]">
                                        <el-input v-model="item.measure_mobile" :placeholder="'请输入师傅电话'" type="data" show-word-limit clearable style="width: 100%;height: 40px;" />
                                    </div>
                                </el-form-item>
                                <el-form-item label="测量照片" style="display: flex;align-items: flex-start;">
                                    <div class="w-60">
                                        <material-picker v-model="item.measure_photos" :limit="9" />
                                    </div>
                                </el-form-item>
                                <el-form-item>
                                    <template #label>
                                        <el-button type="danger" @click="measureCoForm.list.splice(index, 1)">删除</el-button>
                                    </template>
                                </el-form-item>
                                
                            </div>
                        </el-form>
                    </template>
                </div>
                <!-- 交底 -->
                <div class="xl:flex flex-row" style="flex-wrap: wrap;" v-if="formData.is_disclose == 1" v-perms="['order.disclose']">
                    <template v-for="(item, index) in discloseCo" :key="index">
                        <el-form-item :label="item.name" :prop="item.column_name" :label-width="80" style="display: flex;align-items: flex-start;">
                            <div>
                                <div v-if="item.type == 'input'" class="w-[200px]">
                                    <el-input v-model="formData[item.column_name]" :placeholder="'请输入' + item.name"
                                        type="data" show-word-limit clearable style="width: 100%;height: 40px;" />
                                </div>
                                <div v-if="item.type == 'date'" class="w-[200px]">
                                    <el-date-picker v-model="formData[item.column_name]" type="date" placeholder="选择日期"
                                        format="YYYY-MM-DD" value-format="x" style="width: 100%;height: 40px;">
                                    </el-date-picker>
                                </div>
                                <div v-if="item.type == 'upload'" class="w-60">
                                    <material-picker v-model="formData[item.column_name]" :limit="9" />
                                </div>
                            </div>
                        </el-form-item>
                    </template>
                </div>
                <!-- 支付 -->
                <div class="xl:flex flex-row" style="flex-wrap: wrap;" v-if="formData.is_pay == 1" v-perms="['order.orderPay']">
                    <template v-for="(item, index) in payCo" :key="index">
                        <el-form-item :label="item.name" :prop="item.column_name" :label-width="80" style="display: flex;align-items: flex-start;">
                            <div>
                                <div v-if="item.type == 'input'" class="w-[200px]">
                                    <el-input v-model="formData[item.column_name]" :placeholder="'请输入' + item.name"
                                        type="data" show-word-limit clearable style="width: 100%;height: 40px;" />
                                </div>
                                <div v-if="item.type == 'date'" class="w-[200px]">
                                    <el-date-picker v-model="formData[item.column_name]" type="date" placeholder="选择日期"
                                        format="YYYY-MM-DD" value-format="x" style="width: 100%;height: 40px;">
                                    </el-date-picker>
                                </div>
                                <div v-if="item.type == 'upload'" class="w-60">
                                    <material-picker v-model="formData[item.column_name]" :limit="9" />
                                </div>
                            </div>
                        </el-form-item>
                    </template>
                </div>
                <!-- ========================================================================================================================== -->
                <!-- 改管列表 -->
                <div v-if="formData.is_change == 1" v-perms="['order.changeManagement']">
                    <el-button type="primary" @click="addChangeItem">添加改管项</el-button>
                </div>
                <div  class="xl:flex flex-row" style="flex-wrap: wrap;" v-if="formData.is_change == 1" v-perms="['order.changeManagement']">
                    <template v-for="(item, index) in changeCoForm.list" :key="index">
                        <el-form :model="item" label-width="80px">
                            <div  class="xl:flex flex-row" style="flex-wrap: wrap;">
                                <el-form-item label="改管时间" :prop="item.change_time" style="display: flex;align-items: flex-start;">
                                    <div class="w-[200px]">
                                        <el-date-picker v-model="item.change_time" type="date" placeholder="选择日期"
                                            format="YYYY-MM-DD" value-format="x" style="width: 100%;height: 40px;">
                                        </el-date-picker>
                                    </div>
                                </el-form-item>
                                <el-form-item label="改管师傅" :prop="item.change_name" style="display: flex;align-items: flex-start;">
                                    <div class="w-[200px]">
                                        <el-input v-model="item.change_name" :placeholder="'请输入改管师傅'" type="data" show-word-limit clearable style="width: 100%;height: 40px;" />
                                    </div>
                                </el-form-item>
                                <el-form-item label="师傅电话" :prop="item.change_mobile" style="display: flex;align-items: flex-start;">
                                    <div class="w-[200px]">
                                        <el-input v-model="item.change_mobile" :placeholder="'请输入师傅电话'" type="data" show-word-limit clearable style="width: 100%;height: 40px;" />
                                    </div>
                                </el-form-item>
                                <el-form-item label="改管照片" style="display: flex;align-items: flex-start;">
                                    <div class="w-60">
                                        <material-picker v-model="item.change_photos" :limit="9" />
                                    </div>
                                </el-form-item>
                                <el-form-item>
                                    <template #label>
                                        <el-button type="danger" @click="changeCoForm.list.splice(index, 1)">删除</el-button>
                                    </template>
                                </el-form-item>
                                
                            </div>
                        </el-form>
                    </template>
                </div>
                <!-- ========================================================================================================================== -->
                
                
                <!-- ========================================================================================================================== -->
                <!-- 下单列表 -->
                <div v-if="formData.is_order == 1" v-perms="['order.is_order']">
                    <el-button type="primary" @click="addOrderItem">添加下单项</el-button>
                </div>
                <div  class="xl:flex flex-row" style="flex-wrap: wrap;" v-if="formData.is_order == 1" v-perms="['order.is_order']">
                    <template v-for="(item, index) in orderCoForm.list" :key="index">
                        <el-form :model="item" label-width="80px">
                            <div  class="xl:flex flex-row" style="flex-wrap: wrap;">
                                <el-form-item label="下单时间" :prop="item.order_time" style="display: flex;align-items: flex-start;">
                                    <div class="w-[200px]">
                                        <el-date-picker v-model="item.order_time" type="date" placeholder="选择日期"
                                            format="YYYY-MM-DD" value-format="x" style="width: 100%;height: 40px;">
                                        </el-date-picker>
                                    </div>
                                </el-form-item>
                                <el-form-item label="下单师傅" :prop="item.order_name" style="display: flex;align-items: flex-start;">
                                    <div class="w-[200px]">
                                        <el-input v-model="item.order_name" :placeholder="'请输入下单师傅'" type="data" show-word-limit clearable style="width: 100%;height: 40px;" />
                                    </div>
                                </el-form-item>
                                <el-form-item label="师傅电话" :prop="item.order_mobile" style="display: flex;align-items: flex-start;">
                                    <div class="w-[200px]">
                                        <el-input v-model="item.order_mobile" :placeholder="'请输入师傅电话'" type="data" show-word-limit clearable style="width: 100%;height: 40px;" />
                                    </div>
                                </el-form-item>
                                <el-form-item label="下单照片" style="display: flex;align-items: flex-start;">
                                    <div class="w-60">
                                        <material-picker v-model="item.order_photos" :limit="9" />
                                    </div>
                                </el-form-item>
                                <el-form-item>
                                    <template #label>
                                        <el-button type="danger" @click="orderCoForm.list.splice(index, 1)">删除</el-button>
                                    </template>
                                </el-form-item>
                                
                            </div>
                        </el-form>
                    </template>
                </div>
                <!-- ========================================================================================================================== -->
                <!-- 发货 -->
                <div class="xl:flex flex-row" style="flex-wrap: wrap;" v-if="formData.is_send == 1" v-perms="['order.consignment']">
                    <template v-for="(item, index) in sendCo" :key="index">
                        <el-form-item :label="item.name" :prop="item.column_name" :label-width="80" style="display: flex;align-items: flex-start;">
                            <div class="w-[200px]">
                                <div>
                                    <el-date-picker v-model="formData[item.column_name]" type="date" placeholder="选择日期"
                                        format="YYYY-MM-DD" value-format="x" style="width: 100%;height: 40px;">
                                    </el-date-picker>
                                </div>
                            </div>
                        </el-form-item>
                    </template>
                </div>
                <!-- ========================================================================================================================== -->
                <!-- 安装列表 -->
                <div v-if="formData.is_install == 1" v-perms="['order.install']">
                    <el-button type="primary" @click="addInstallItem">添加安装项</el-button>
                </div>
                <div  class="xl:flex flex-row" style="flex-wrap: wrap;" v-if="formData.is_install == 1" v-perms="['order.install']">
                    <template v-for="(item, index) in installCoForm.list" :key="index">
                        <el-form :model="item" label-width="80px">
                            <div  class="xl:flex flex-row" style="flex-wrap: wrap;">
                                <el-form-item label="安装时间" :prop="item.install_time" style="display: flex;align-items: flex-start;">
                                    <div class="w-[200px]">
                                        <el-date-picker v-model="item.install_time" type="date" placeholder="选择日期"
                                            format="YYYY-MM-DD" value-format="x" style="width: 100%;height: 40px;">
                                        </el-date-picker>
                                    </div>
                                </el-form-item>
                                <el-form-item label="安装师傅" :prop="item.install_name" style="display: flex;align-items: flex-start;">
                                    <div class="w-[200px]">
                                        <el-input v-model="item.install_name" :placeholder="'请输入安装师傅'" type="data" show-word-limit clearable style="width: 100%;height: 40px;" />
                                    </div>
                                </el-form-item>
                                <el-form-item label="师傅电话" :prop="item.install_mobile" style="display: flex;align-items: flex-start;">
                                    <div class="w-[200px]">
                                        <el-input v-model="item.install_mobile" :placeholder="'请输入师傅电话'" type="data" show-word-limit clearable style="width: 100%;height: 40px;" />
                                    </div>
                                </el-form-item>
                                <el-form-item label="安装照片" style="display: flex;align-items: flex-start;">
                                    <div class="w-60">
                                        <material-picker v-model="item.install_photos" :limit="9" />
                                    </div>
                                </el-form-item>
                                <el-form-item>
                                    <template #label>
                                        <el-button type="danger" @click="installCoForm.list.splice(index, 1)">删除</el-button>
                                    </template>
                                </el-form-item>
                                
                            </div>
                        </el-form>
                    </template>
                </div>
                <!-- ========================================================================================================================== -->
                <!-- 收货 -->
                <div class="xl:flex flex-row" style="flex-wrap: wrap;" v-if="formData.is_receive == 1" v-perms="['order.receiving']">
                    <template v-for="(item, index) in receiveCo" :key="index">
                        <el-form-item :label="item.name" :prop="item.column_name" :label-width="80" style="display: flex;align-items: flex-start;">
                            <div class="w-[200px]">
                                <div>
                                    <el-date-picker v-model="formData[item.column_name]" type="date" placeholder="选择日期"
                                        format="YYYY-MM-DD" value-format="x" style="width: 100%;height: 40px;">
                                    </el-date-picker>
                                </div>
                                
                            </div>
                        </el-form-item>
                    </template>
                </div>
                <!-- <el-form-item label="订单状态">
                    <el-select v-model="formData.status" placeholder="请选择订单状态" style="width: 100%;height: 40px;">
                        <el-option label="待处理" value="pending" />
                        <el-option label="处理中" value="processing" />
                        <el-option label="已完成" value="completed" />
                        <el-option label="已取消" value="cancelled" />
                    </el-select>
                </el-form-item> -->
                <div class="flex justify-center mt-4">
                    <el-button type="primary" @click="handleSubmit">保存</el-button>
                    <el-button @click="$router.back()">取消</el-button>
                </div>
            </el-form>
        </el-card>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { orderDetail, orderAdd, orderEdit } from '@/api/order';
import { goodsGet_skus, goodsLists } from '@/api/goods';
import feedback from '@/utils/feedback';
import useAppStore from '@/stores/modules/app'
import useUserStore from '@/stores/modules/user'
import config from '@/config'
const route = useRoute();
const router = useRouter();

const userStore = useUserStore()
const appStore = useAppStore()
const action = ref(`${config.baseUrl}${config.urlPrefix}/upload/image`)
console.log(action.value, "action")
const headers = computed(() => ({
    token: userStore.token,
    version: appStore.config.version
}))
const columnArr = reactive([
    {
        column_name: 'shop_title',
        name: '店名',
        type: 'input'
    },
    {
        column_name: 'shop_name',
        name: '店员',
        type: 'input'
    },
    {
        column_name: 'material',
        name: '主材',
        type: 'input'
    },
    {
        column_name: 'task',
        name: '任务',
        type: 'input'
    },
    {
        column_name: 'foreman',
        name: '工长',
        type: 'input'
    },
    {
        column_name: 'quality',
        name: '材质',
        type: 'input'
    },
    {
        column_name: 'group_square',
        name: '平米或组数',
        type: 'input'
    },
    {
        column_name: 'is_all_pipe',
        name: '是否全屋换管',
        type: 'input'
    },
    {
        column_name: 'heating_method',
        name: '供暖方式',
        type: 'input'
    },
    {
        column_name: 'pipe_type',
        name: '管材类型',
        type: 'input'
    },
    {
        column_name: 'old_heating',
        name: '原暖气',
        type: 'input'
    },
    {
        column_name: 'new_heating',
        name: '新暖气',
        type: 'input'
    },
    {
        column_name: 'manage_name',
        name: '管家姓名',
        type: 'input'
    },
    {
        column_name: 'manage_mobile',
        name: '管家电话',
        type: 'input'
    },
    {
        column_name: 'customer_name',
        name: '客户姓名',
        type: 'input'
    },
    {
        column_name: 'customer_mobile',
        name: '客户电话',
        type: 'input'
    },
    {
        column_name: 'customer_address',
        name: '客户地址',
        type: 'input'
    },
    {
        column_name: 'contract_no',
        name: '合同编号',
        type: 'input'
    },
    {
        column_name: 'remark',
        name: '备注',
        type: 'input'
    }
])

const limits = reactive([
    {
        column_name: 'is_measure',
        name: '是否测量',
        type: 'checkbox',
        limit: 'order.measurement',
    },
    {
        column_name: 'is_disclose',
        name: '是否交底',
        type: 'checkbox',
        limit: 'order.disclose',
    },
    {
        column_name: 'is_pay',
        name: '是否支付',
        type: 'checkbox',
        limit: 'order.orderPay',
    },
    {
        column_name: 'is_change',
        name: '是否改管',
        type: 'checkbox',
        limit: 'order.changeManagement',
    },
    {
        column_name: 'is_order',
        name: '是否下单',
        type: 'checkbox',
        limit: 'order.downOrder',
    },
    {
        column_name: 'is_send',
        name: '是否发货',
        type: 'checkbox',
        limit: 'order.consignment',
    },
    {
        column_name: 'is_install',
        name: '是否安装',
        type: 'checkbox',
        limit: 'order.install',
    },
    {
        column_name: 'is_receive',
        name: '是否收货',
        type: 'checkbox',
        limit: 'order.receiving',
    },
    {
        column_name: 'is_success',
        name: '是否成单',
        type: 'checkbox',
        limit: 'order.successOrder',
    }
])
// 测量
const measureCoForm = reactive({
    list: [
        {
            measure_time: '',
            measure_name: '',
            measure_mobile: '',
            measure_photos: []
        }
    ]
})
// 改管
const  changeCoForm = reactive({
    list: [
        {
            change_time: '',
            change_name: '',
            change_mobile: '',
            change_photos: []
        }
    ]
})
// 下单
const orderCoForm = reactive({
    list: [
        {
            order_time: '',
            order_name: '',
            order_mobile: '',
            order_photos: []
        }
    ]
})
// 安装
const installCoForm = reactive({
    list: [
        {
            install_time: '',
            install_name: '',
            install_mobile: '',
            install_photos: []
        }
    ]
})

const payCo = reactive([
    {
        column_name: 'pay_time',
        name: '支付时间',
        type: 'date'
    },
    {
        column_name: 'pay_money',
        name: '支付金额',
        type: 'input'
    },
    {
        column_name: 'pay_photos',
        name: '支付图片',
        type: 'upload'
    }
])


const discloseCo = reactive([
    {
        column_name: 'disclose_time',
        name: '交底日期',
        type: 'date'
    },
    {
        column_name: 'disclose_name',
        name: '交底师傅',
        type: 'input'
    },
    {
        column_name: 'disclose_mobile',
        name: '师傅电话',
        type: 'input'
    },
    {
        column_name: 'disclose_photos',
        name: '交底图片',
        type: 'upload'
    }
])


// 送货
const sendCo = reactive([
    {
        column_name: 'send_time',
        name: '送货时间',
        type: 'date'
    }
])
// 收货
const receiveCo = reactive([
    {
        column_name: 'receive_time',
        name: '收货时间',
        type: 'date'
    }
])
const formData = reactive<{
    [key: string]: any
}>({
    shop_title: '',
    shop_name: '',
    material: '',
    customer_name: '',
    customer_mobile: '',
    customer_address: '',
    contract_no: '',
    // measure_time: '',
    // measure_name: '',
    // measure_photos: [],
    is_measure: 0,
    pay_time: '',
    pay_money: 0,
    pay_photos: [],
    is_pay: 0,
    // change_time: '',
    // change_name: '',
    // change_photos: [],
    is_change: 0,
    is_send: 0,
    send_time: '',
    receive_time: '',
    is_receive: 0,
    // install_time: '',
    // install_name: '',
    // install_photos: [],
    is_install: 0,
    remark: '',
    status: 0,
    skus: [],
    info_photos: [],
    is_disclose: 0,
    disclose_time: '',
    disclose_name: '',
    disclose_photos: [],
    is_order: 0,
    // order_time: '',
    // order_name: '',
    // order_photos: [],
    task: '',
    foreman: '',
    quality: '',
    is_all_pipe: '',
    heating_method: '',
    pipe_type: '',
    old_heating: '',
    new_heating: '',
    manage_name: '',
    manage_mobile: '',
    group_square: '',

    install_json: [],
    measure_json: [],
    order_json: [],
    change_json: [],
    is_success: 0
});
const configItemRule = reactive({
    sku_id: [
        {
            required: true,
            message: '请选择商品规格',
            trigger: 'blur'
        }
    ],
    group_number: [
        {
            required: true,
            message: '请输入组号',
            trigger: 'blur'
        }
    ],
    number: [
        {
            required: true,
            message: '请输入数量',
            trigger: 'blur'
        }
    ],
    sale_price: [
        {
            required: true,
            message: '请输入销售价',
            trigger: 'blur'
        }
    ],
    cost_price: [
        {
            required: true,
            message: '请输入成本价',
            trigger: 'blur'
        }
    ],
    
    height: [
        {
            required: true,
            message: '请输入高度',
            trigger: 'blur'
        }
    ],
    
})
// 添加配置项
const addConfigItem = () => {
    formData.skus.push({
        sku_id: '',
        goods_id: '',
        name: '',
        group_number: 0,
        number: 0,
        sale_price: 0,
        cost_price: 0,
        color: '',
        type: '',
        hat_color: '',
        caliber: '',
        series: '',
        height: '',
        method: '',
        special_type: '',
        remark: '',
        unit: ''
    })
}
const skusData = ref<any[]>([])
const getGoodsGet_skus = async () => {
    // const data  = await goodsGet_skus()
    const data  = await goodsLists({page_size: 9999})
    skusData.value = data.lists
}



// 选中商品规格的处理

const selectChange = async (item: any, index: number, e: any) => {
    let data = skusData.value.find((item) => item.id == e)

    // formData.skus[index].name = data?.name
    formData.skus[index].goods_id = data?.id
    formData.skus[index].sku_id = data?.id
    // formData.skus[index].color = data?.goodsInfo.color
    // formData.skus[index].hat_color = data?.goodsInfo.hat_color
    // formData.skus[index].special_type = data?.goodsInfo.special_type
    // formData.skus[index].series = data?.goodsInfo.series
    // formData.skus[index].caliber = data?.goodsInfo.caliber
    // formData.skus[index].method = data?.goodsInfo.method
    // formData.skus[index].type = data?.goodsInfo.type

    for (const key in data) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            formData.skus[index][key] = data[key]
            if(key == 'sale_price' || key == 'cost_price'){
                formData.skus[index][key] = data && data[key]?Number(data[key]) : 0
            }
        }
    }
}

const getDetail = async () => {
    if (route.query.id) {
        const data = await orderDetail({ id: route.query.id });
        Object.assign(formData, data);
        for (const key in formData) {
            if(key != 'pay_photos' && key != 'info_photos' && key != 'disclose_photos' && key != 'pay_time' && key != 'disclose_time' && key != 'receive_time' && key != 'send_time' && key != 'install_json' && key != 'measure_json' && key != 'order_json' && key != 'change_json'){
                if (data[key] != null && data[key] != undefined) {
                    //@ts-ignore
                    formData[key] = data[key]
                }
            }

            if(key == 'pay_photos' || key == 'info_photos' || key == 'disclose_photos'){
                if(data[key] != '' && data[key] != null && data[key] != undefined){
                    formData[key] = data[key].split(',')
                }else{
                    formData[key] = []
                }
            }
            if(key == 'pay_time' || key == 'disclose_time' || key == 'receive_time' || key == 'send_time'){
                if(data[key] != '' && data[key] != null && data[key] != undefined){
                    formData[key] = data[key] * 1000
                }else{
                    formData[key] = ''
                }
            }

            if(key == 'install_json' || key == 'measure_json' || key == 'order_json' || key == 'change_json'){
                if(data[key] != '' && data[key] != null && data[key] != undefined){
                    let list = data[key].length > 0 ? JSON.parse(JSON.stringify(data[key])) : []
                    list.forEach((itemObj: any) => {
                        for(const keys in itemObj){
                            if(keys == 'measure_photos' || keys == 'install_photos' || keys == 'order_photos' || keys == 'change_photos'){
                                if(itemObj[keys] != '' && itemObj[keys] != null && itemObj[keys] != undefined){
                                    itemObj[keys] = itemObj[keys].split(',')
                                }else{
                                    itemObj[keys] = []
                                }
                            }

                            if(keys == 'measure_time' || keys == 'install_time' || keys == 'order_time' || keys == 'change_time'){
                                if(itemObj[keys] != '' && itemObj[keys] != null && itemObj[keys] != undefined){
                                    itemObj[keys] = Number(itemObj[keys] * 1000)
                                }else{
                                    itemObj[keys] = 0
                                }
                            }
                        }
                    })
                    formData[key] = list

                    if(key == 'measure_json'){
                        measureCoForm.list = list
                    }
                    if(key == 'change_json'){
                        changeCoForm.list = list
                    }
                    if(key == 'order_json'){
                        orderCoForm.list = list
                    }
                    if(key == 'install_json'){
                        installCoForm.list = list
                    }
                }
            }
        }
    }
};
// 声明表单 formRef
// 用来存储 SKU 表单 refs 的 Map
// Key 可以是 index 或 item.id (如果 item.id 唯一且稳定的话)
const skuFormRefs = ref(new Map()); 
// 设置 SKU 表单 ref 的函数
const setSkuFormRef = (index, el) => {
    if (el) {
        // 存储 el-form 组件实例
        skuFormRefs.value.set(index, el);
    } else {
        // 如果元素被移除，从 Map 中删除对应的 ref
        skuFormRefs.value.delete(index);
    }
};
// 可选：在更新前清空 refs，确保准确性（特别是当列表结构变化频繁时）
onBeforeUpdate(() => {
  skuFormRefs.value.clear();
});
const handleSubmit = async () => {
    let allValid = true;
    const formPromises = []; // 收集所有验证 Promise

    // 遍历 Map 中的所有表单实例
    for (const [index, formInstance] of skuFormRefs.value.entries()) {
        if (formInstance) {
             // 调用每个表单实例的 validate 方法
             // validate 方法返回一个 Promise
             formPromises.push(
                 formInstance.validate().then(valid => {
                     if (!valid) {
                         allValid = false;
                         console.log(`SKU表单 ${index} 验证失败.`);
                     } else {
                          console.log(`SKU表单 ${index} 验证通过.`);
                     }
                     return valid; // 返回验证结果
                 }).catch(error => {
                     allValid = false;
                     console.error(`验证 SKU表单 ${index} 时出错:`, error);
                     return false; // 发生错误也视为验证失败
                 })
             );
        }
    }

    await Promise.all(formPromises);
    if (!allValid) {
        feedback.msgError('请填写必填项');
        return;
    }

    let formDataCopy = JSON.parse(JSON.stringify(formData));

    if(formData.is_measure == 1) {
        measureCoForm.list.forEach((item: any, index: number) => {
            if(item.measure_photos.length > 0) {
                item.measure_photos = item.measure_photos.join(',');
            }else{
                item.measure_photos = '';
            }

            if(item.measure_time && item.measure_time != 0) {
                item.measure_time = Number(item.measure_time / 1000)
            }else{
                item.measure_time = 0
            }
        })
        formDataCopy.measure_json = measureCoForm.list;
    }
    console.log(toRaw(formDataCopy.measure_json), formDataCopy.measure_json)
    if(formData.is_change == 1) {
        changeCoForm.list.forEach((item: any, index: number) => {
            if(item.change_photos.length > 0) {
                item.change_photos = item.change_photos.join(',');
            }else{
                item.change_photos = '';
            }

            if(item.change_time && item.change_time != 0) {
                item.change_time = Number(item.change_time / 1000)
            }else{
                item.change_time = 0
            }
        })
        formDataCopy.change_json = changeCoForm.list;
    }
    if(formData.is_install == 1) {
        installCoForm.list.forEach((item: any, index: number) => {
            if(item.install_photos.length > 0) {
                item.install_photos = item.install_photos.join(',');
            }else{
                item.install_photos = '';
            }

            if(item.install_time && item.install_time != 0) {
                item.install_time = Number(item.install_time / 1000)
            }else{
                item.install_time = 0
            }
        })
        formDataCopy.install_json = installCoForm.list;
    }
    if(formData.is_order == 1) {
        orderCoForm.list.forEach((item: any, index: number) => {
            if(item.order_photos.length > 0) {
                item.order_photos = item.order_photos.join(',');
            }else{
                item.order_photos = '';
            }

            if(item.order_time && item.order_time != 0) {
                item.order_time = Number(item.order_time / 1000)
            }else{
                item.order_time = 0
            }
        })
        formDataCopy.order_json = orderCoForm.list;
    }



    if(formData.info_photos.length > 0) {
        formDataCopy.info_photos = formData.info_photos.join(',');
    }else{
        formDataCopy.info_photos = '';
    }
    
    if(formData.pay_photos.length > 0) {
        formDataCopy.pay_photos = formData.pay_photos.join(',');
    }else{
        formDataCopy.pay_photos = '';
    }
    
    if(formData.disclose_photos.length > 0) {
        formDataCopy.disclose_photos = formData.disclose_photos.join(',');
    }else{
        formDataCopy.disclose_photos = '';
    }
    

    if(formData.is_send == 1 && formData.send_time && formData.send_time != 0) {
        formDataCopy.send_time = Number(formData.send_time / 1000)
    }else{
        formDataCopy.send_time = 0
    }
    if(formData.is_receive == 1 && formData.receive_time && formData.receive_time != 0) {
        formDataCopy.receive_time = Number(formData.receive_time / 1000)
    }else{
        formDataCopy.receive_time = 0
    }
    
    if(formData.is_pay == 1 && formData.pay_time && formData.pay_time != 0) {
        formDataCopy.pay_time = Number(formData.pay_time / 1000)
    }else{
        formDataCopy.pay_time = 0
    }
    if(formData.is_disclose == 1 && formData.disclose_time && formData.disclose_time != 0) {
        formDataCopy.disclose_time = Number(formData.disclose_time / 1000)
    }else{
        formDataCopy.disclose_time = 0
    }
    
    
    
    
    try {
        await orderEdit(formDataCopy);
        feedback.msgSuccess('保存成功');
        router.back();
    } catch (error) {
        feedback.msgError('保存失败');
    }
};

// 测量
const addMeasureItem = () => {
    measureCoForm.list.push({
        measure_time: '',
        measure_name: '',
        measure_mobile: '',
        measure_photos: []
    })
}
// 改管
const addChangeItem = () => {
    changeCoForm.list.push({
        change_time: '',
        change_name: '',
        change_mobile: '',
        change_photos: []
    })
}
// 下单
const addOrderItem = () => {
    orderCoForm.list.push({
        order_time: '',
        order_name: '',
        order_mobile: '',
        order_photos: []
    })
}
// 安装
const addInstallItem = () => {
    installCoForm.list.push({
        install_time: '',
        install_name: '',
        install_mobile: '',
        install_photos: []
    })
}

onMounted(() => {
    getDetail();
    getGoodsGet_skus()
});
</script>

<style scoped>
.config-key-input {
    width: 200px;
    height: 40px;
}
</style>